const Router = require('koa-router');
const db = require('../models/db');
const authenticate = require('../middleware/auth');

const router = new Router();

// 创建笔记
router.post('/', authenticate, async (ctx) => {
  const { title, content, domain, url, is_public } = ctx.request.body;
  const userId = ctx.state.user.id;

  if (!title || !content) {
    ctx.status = 400;
    ctx.body = { error: 'Title and content are required' };
    return;
  }

  try {
    const result = await db.query(
      'INSERT INTO notes (user_id, title, content, domain, url, is_public) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
      [userId, title, content, domain || '', url || '', typeof is_public === 'boolean' ? is_public : false]
    );
    ctx.status = 201;
    ctx.body = result.rows[0];
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error creating note:', err);
  }
});

// 获取当前用户的所有笔记
router.get('/', authenticate, async (ctx) => {
  const userId = ctx.state.user.id;
  try {
    const result = await db.query('SELECT * FROM notes WHERE user_id = $1 ORDER BY updated_at DESC', [userId]);
    ctx.body = result.rows;
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error fetching notes:', err);
  }
});

// 根据 URL 和 user_id 查询笔记
router.get('/query', authenticate, async (ctx) => {
  const { url } = ctx.query; // 从查询参数中获取 URL
  const userId = ctx.state.user.id;

  if (!url) {
    ctx.status = 400;
    ctx.body = { error: 'URL parameter is required' };
    return;
  }

  try {
    const result = await db.query('SELECT * FROM notes WHERE url = $1 AND user_id = $2', [url, userId]);
    if (result.rows.length === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Note not found with the given URL for this user' };
      return;
    }
    ctx.body = result.rows; // 可能有多条笔记匹配同一个 URL，返回数组
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error fetching note by URL:', err);
  }
});

// 获取特定笔记
router.get('/:id', authenticate, async (ctx) => {
  const noteId = ctx.params.id;
  const userId = ctx.state.user.id;
  try {
    const result = await db.query('SELECT * FROM notes WHERE id = $1 AND user_id = $2', [noteId, userId]);
    if (result.rows.length === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Note not found or access denied' };
      return;
    }
    ctx.body = result.rows[0];
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error fetching note:', err);
  }
});

// 更新笔记
router.put('/:id', authenticate, async (ctx) => {
  const noteId = ctx.params.id;
  const userId = ctx.state.user.id;
  const { title, content, domain, url, is_public } = ctx.request.body;

  // 至少需要一个字段用于更新
  if (title === undefined && content === undefined && domain === undefined && url === undefined && is_public === undefined) {
    ctx.status = 400;
    ctx.body = { error: 'At least one field (title, content, domain, url, is_public) must be provided for update' };
    return;
  }

  try {
    const selectResult = await db.query('SELECT * FROM notes WHERE id = $1 AND user_id = $2', [noteId, userId]);
    if (selectResult.rows.length === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Note not found or access denied' };
      return;
    }

    const existingNote = selectResult.rows[0];
    const newTitle = title !== undefined ? title : existingNote.title;
    const newContent = content !== undefined ? content : existingNote.content;
    const newDomain = domain !== undefined ? domain : existingNote.domain;
    const newUrl = url !== undefined ? url : existingNote.url;
    const newIsPublic = is_public !== undefined ? is_public : existingNote.is_public;

    const updateResult = await db.query(
      'UPDATE notes SET title = $1, content = $2, domain = $3, url = $4, is_public = $5, updated_at = NOW() WHERE id = $6 AND user_id = $7 RETURNING *',
      [newTitle, newContent, newDomain, newUrl, newIsPublic, noteId, userId]
    );

    ctx.body = updateResult.rows[0];
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error updating note:', err);
  }
});

// 删除笔记
router.delete('/:id', authenticate, async (ctx) => {
  const noteId = ctx.params.id;
  const userId = ctx.state.user.id;
  try {
    const result = await db.query('DELETE FROM notes WHERE id = $1 AND user_id = $2 RETURNING *', [noteId, userId]);
    if (result.rows.length === 0) {
      ctx.status = 404;
      ctx.body = { error: 'Note not found or access denied' };
      return;
    }
    ctx.status = 204; // No content
  } catch (err) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
    console.error('Error deleting note:', err);
  }
});

module.exports = router;
